package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.article.feign.ArticleFeign;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.common.util.JsonUtils;
import com.usian.model.article.dtos.AuthorDto;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.user.entity.ApUser;
import com.usian.user.entity.ApUserFan;
import com.usian.user.entity.ApUserFollow;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.IApUserFanService;
import com.usian.user.service.IApUserFollowService;
import com.usian.user.service.IApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.usian.common.constants.message.FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-05
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {


    @Autowired
    private ArticleFeign articleFeign;

    @Override
    public void follow(UserRelationDto dto) {
        //1、获取登录用户App Id
        Integer userId = UserThreadLocalUtils.getUserId();
        if(userId==null || userId==0){
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2、获取作者对应的App用户id
        AuthorDto authorDto = articleFeign.findById(dto.getAuthorId());
        if(authorDto==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"关注的作者不存在");
        }
        Integer followId = authorDto.getUserId();
        //判断用户是关注作者还是取消关注作者
        if(dto.getOperation()==1){
            //关注作者
            followUser(userId,followId,dto.getArticleId());
        }else{
            //取消关注作者
            cancelFollowUser(userId,followId);
        }

    }

    @Override
    public ApUserFollow findByUserIdAndFollowId(Integer userId, Integer followId) {
        //根据用户id查询是否关注了该作者
        QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApUserFollow::getUserId,userId).eq(ApUserFollow::getFollowId,followId);
        ApUserFollow apUserFollow = apUserFollowService.getOne(queryWrapper);

        return apUserFollow;
    }

    @Autowired
    private IApUserFollowService apUserFollowService;

    @Autowired
    private IApUserFanService apUserFanService;

    /**
     * 取消关注作者
     * @param userId
     * @param followId
     */
    private void cancelFollowUser(Integer userId, Integer followId) {
        //删除App关注作者数据‘
        QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApUserFollow::getUserId,userId).eq(ApUserFollow::getFollowId,followId);
        boolean b = apUserFollowService.remove(queryWrapper);
        if (!b) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除关注作者数据失败");
        }

        //删除作者粉丝数据
        QueryWrapper<ApUserFan> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(ApUserFan::getUserId,followId).eq(ApUserFan::getFansId,userId);
        boolean b1 = apUserFanService.remove(queryWrapper1);
        if (!b1) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"删除作者关联的粉丝数据失败");
        }
    }


@Autowired
private KafkaTemplate kafkaTemplate;
    /**
     * 用户关注
     * @param userId
     * @param followId
     * @param articleId
     */
    private void followUser(Integer userId, Integer followId, Long articleId) {
        //查询作者对应的App用户是否存在
        ApUser apUser = this.getById(followId);
        if(apUser==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"作者关联的App用户不存在");
        }
        //查询当前用户是否关注过作者
        QueryWrapper<ApUserFollow> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApUserFollow::getUserId,userId).eq(ApUserFollow::getFollowId,followId);
        int count = apUserFollowService.count(queryWrapper);
        if(count>0){
            throw new LeadException(AppHttpCodeEnum.DATA_EXIST,"用户已经关注了该作者");
        }
        //记录用户关注作者信息
        ApUserFollow userFollow = new ApUserFollow();
        userFollow.setUserId(userId);
        userFollow.setFollowId(followId);
        userFollow.setFollowName(apUser.getName());
        userFollow.setLevel(0);
        userFollow.setIsNotice(true);
        userFollow.setCreatedTime(new Date());
        boolean b = apUserFollowService.save(userFollow);
        if(!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存关注数据失败");
        }

        //查询粉丝用户是否存在
        ApUser fanUser = this.getById(userId);
        if(fanUser==null){
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST,"粉丝用户数据不存在");
        }
        //查询作者是否有当前粉丝
        QueryWrapper<ApUserFan> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(ApUserFan::getUserId,followId).eq(ApUserFan::getFansId,userId);
        ApUserFan userFan = apUserFanService.getOne(queryWrapper1);
        if(userFan==null){
            //作者没有关联到当前粉丝，保存作者与粉丝关联关系
            userFan = new ApUserFan();
            userFan.setFansId(userId);
            userFan.setUserId(followId);
            userFan.setFansName(fanUser.getName());
            userFan.setLevel(0);
            userFan.setCreatedTime(new Date());
            userFan.setIsDisplay(true);
            userFan.setIsShieldComment(false);
            userFan.setIsShieldLetter(false);
            boolean b1 = apUserFanService.save(userFan);
            if(!b1){
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR,"保存粉丝数据失败");
            }
        }

        //生产消息，完成记录用户关注行为
        FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
        followBehaviorDto.setArticleId(articleId);
        followBehaviorDto.setUserId(userId);
        followBehaviorDto.setFollowId(followId);
        kafkaTemplate.send(FOLLOW_BEHAVIOR_TOPIC, JsonUtils.toString(followBehaviorDto));
//
    }
}
